import { defineStore } from '@mpxjs/pinia'
import { ref } from '@mpxjs/core'
import { CDN_HOST } from './config'

type IApp = {
  audioContext: WechatMiniprogram.InnerAudioContext
  isPlay: boolean
}

export const useAppStore = defineStore('app', () => {
  const app = ref<IApp>({
    audioContext: wx.createInnerAudioContext({
      useWebAudioImplement: true // 是否使用 WebAudio 作为底层音频驱动，默认关闭。对于短音频、播放频繁的音频建议开启此选项，开启后将获得更优的性能表现。由于开启此选项后也会带来一定的内存增长，因此对于长音频建议关闭此选项
    }),
    isPlay: false
  })

  const setup = () => {
    app.value.audioContext.src = `${CDN_HOST}/music/music.mp3`
    app.value.audioContext.loop = true
    app.value.audioContext.autoplay = true
    wx.setInnerAudioOption({
      obeyMuteSwitch: false,
      mixWithOther: true
    })
    app.value.audioContext.play()
    app.value.isPlay = true
  }

  const changePlay = () => {
    if (app.value.isPlay) {
      app.value.audioContext.pause()
      app.value.isPlay = false
    } else {
      app.value.audioContext.play()
      app.value.isPlay = true
    }
  }

  return {
    app,
    setup,
    changePlay
  }
})
